const Router = require("koa-router");
const mysql = require("mysql");
const http = require("../utils/http");

const router = new Router({
    prefix: "/address"
});

// 查询当前登录用户的地址
router.get("/list", async (ctx, next) => {
    console.log("1212");
    // 不要把openid筛选出来
    const openid = ctx.state.openid;
    const sql = "select `id`,`receive_name`,`receive_phone`,`receive_region`,`receive_detail`,`is_default` from `dt_address` where `openid` = ?;";
    const results = await http(sql, [openid]);
    return Promise.resolve(results);
});
// 新增一个地址
router.post("/add", async (ctx, next) => {
    const openid = ctx.state.openid;
    let {
        receive_name,
        receive_phone,
        receive_region,
        receive_detail
    } = ctx.request.body;

    const sql = "insert into `dt_address` (`openid`,`receive_name`,`receive_phone`,`receive_region`,`receive_detail`) values (?,?,?,?,?);";
    const results = await http(sql, [openid, receive_name,
        receive_phone,
        receive_region,
        receive_detail
    ]);

    if (results.affectedRows === 1) {
        return Promise.resolve(results.insertId);
    } else return Promise.reject("新增一个失败");
});
// 修改一个地址
router.post("/update", async (ctx, next) => {
    const {
        id,
        receive_name,
        receive_phone,
        receive_region,
        receive_detail
    } = ctx.request.body;
    const sql = 'update `dt_address` set `receive_name`=?,`receive_phone`=?,`receive_region`=?,`receive_detail`=? where `id`=?;';
    const results = await http(sql, [receive_name, receive_phone, receive_region, receive_detail, id]);
    if (results.affectedRows === 1)
        return Promise.resolve();
    else
        return Promise.reject('地址修改失败..');
});
// 删除一个地址
router.get("/remove/:id", async (ctx, next) => {
    const id = parseInt(ctx.params.id);
    const sql = "call p_removeAddress(?);";
    const results = await http(sql, [id]);
    if (results[0][0].result === "") {
        return Promise.resolve();
    } else {
        return Promise.reject(results[0][0].result);
    }

});
// 设置为默认地址
router.get("/set_default/:id", async (ctx, next) => {
    const openid = ctx.state.openid;
    let id = parseInt(ctx.params.id);
    const sql = 'update `dt_address` set `is_default` = 0 where `openid` = ?;update `dt_address` set `is_default` = 1 where `id` = ?;';
    await http(sql, [openid, id], {
        multipleStatements: true // 用来执行多行sql语句 
    });
    return Promise.resolve();

});

// 获取某个用户的默认地址
router.get("/get_default", async (ctx, next) => {
    const openid = ctx.state.openid;
    const sql = 'select `id`,`receive_name`,`receive_phone`,`receive_region`,`receive_detail`,`is_default` from `dt_address` where `openid` = ? and `is_default` = 1';
    const results = await http(sql, [openid]);
    // return Promise.resolve(results[0] || null); 不希望返回一个undefine
    return Promise.resolve(results[0]);
});

module.exports = router.routes();